/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-05-06
 * Time: 14:07
 */
public class Sort {

    private void swap(int[] arr, int x, int y) {
        int tmp = arr[x];
        arr[x] = arr[y];
        arr[y] = tmp;
    }

    /**
     * 插入排序
     */
    public void InsertSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int tmp = arr[i];
            int j = i - 1;
            while (j >= 0) {
                if (arr[j] > tmp) {
                    arr[j + 1] = arr[j];
                } else {
                    arr[j + 1] = tmp;
                    break;//说明当前有序了,
                }
                j--;
            }
            arr[j + 1] = tmp;
        }
    }

    /**
     * 希尔排序
     */
    public void ShellSort(int[] arr) {
        int gap = arr.length;
        while (gap > 1) {
            gap /= 2;
            shell(arr, gap);
        }
    }

    private void shell(int[] arr, int gap) {
        for (int i = 0; i < arr.length; i++) {
            int tmp = arr[i];
            int j = i - gap;
            while (j >= 0) {
                if (arr[j] > tmp) {
                    arr[j + gap] = arr[j];
                } else {
                    arr[j + gap] = tmp;
                    break;//说明当前有序了,
                }
                j -= gap;
            }
            arr[j + gap] = tmp;
        }
    }

    /**
     * 选择排序
     */
    public void SelectSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            swap(arr, minIndex, i);
        }
    }

    /**
     * 堆排序
     */

    public void HeapSort(int[] arr) {
        //升序,建大堆
        createBigHeap(arr);
        int end = arr.length - 1;
        while (end >= 0) {
            swap(arr, 0, end);
            shiftDown(arr, 0, end);
            end--;
        }
    }

    private void createBigHeap(int[] arr) {
        for (int parent = (arr.length - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(arr, parent, arr.length);
        }
    }

    private void shiftDown(int[] arr, int parent, int end) {
        int child = parent * 2 + 1;
        while (child < end) {

            if (child + 1 < end && arr[child] < arr[child + 1]) {
                child++;
            }
            if (arr[child] > arr[parent]) {
                swap(arr, parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }

        }
    }


}
